<template>
  <el-container style="height: 100%; border: 1px solid #eee">
    <el-aside width="300px">
      <vxe-toolbar>
        <template #buttons>
          <vxe-input
            style="width: 98%; padding-left: 5px"
            v-model="roleName"
            type="search"
            placeholder="角色名称搜索"
            v-on:keyup.enter.native="getRolesData"
            @search-click="getRolesData"
          ></vxe-input>
        </template>
      </vxe-toolbar>
      <vxe-table
        :show-header="true"
        border
        height="440"
        show-header-overflow
        show-overflow
        row-id="id"
        :row-config="{ isHover: true }"
        :data="rolesData"
        @cell-click="handleCellClick"
      >
        <vxe-column type="seq" width="60"></vxe-column>
        <vxe-column field="roleName" title="角色名称"></vxe-column>
      </vxe-table>
    </el-aside>
    <el-main>
      <vxe-toolbar>
        <template #buttons>
          <vxe-button icon="fa fa-plus" @click="doSave()">保存</vxe-button>
        </template>
      </vxe-toolbar>
      <os-grid
        :show-header="true"
        border
        show-header-overflow
        show-overflow
        ref="usersTable"
        row-id="id"
        action="system/userPage"
        :row-config="{ isHover: true }"
        :page="true"
        :columns="columns"
        :checkbox-config="{ highlight: true }"
        @selectData="selectData"
        @checkbox-all="handleCheckAll"
        @checkbox-change="handleCheckChange"
      >
      </os-grid>
    </el-main>
  </el-container>
</template>
<script>
import OsGrid from '../../components/OsGrid.vue'
export default {
  components: { OsGrid },
  name: 'RoleAuthInfo',
  data () {
    return {
      loading1: false,
      roleName: '', // 角色名称查询
      rolesData: [],
      usersData: [],
      roleRow: null, // 选中的角色行对象
      roleUserData: [], // 已存在的用户与角色关系
      tempCheckedData: new Set(), // 用于临时存储选择的数据ID
      url: {
        roleAll: 'system/roleAll',
        userList: 'system/userPage',
        roleUserList: 'system/queryUserRoleByRoleId',
        saveData: 'system/saveUserRoleByRoleId'
      },
      columns: [
        { type: 'checkbox', title: '', width: 50 },
        { title: '用户账号', field: 'userName' },
        { title: '真实姓名', field: 'realName' }
      ]
    }
  },
  mounted () {
    this.getRolesData()
  },
  methods: {
    async getRolesData () {
      this.loading1 = true
      const { data } = await this.$store.dispatch(this.url.roleAll, {
        roleName: this.roleName
      })
      this.rolesData = [...data]
      this.loading1 = false
    },
    /** 选中数据 */
    selectData (rows) {
      const usersTable = this.$refs.usersTable.getGrid()
      this.$nextTick(() => {
        if (rows && rows.length > 0) {
          rows.forEach((e) => {
            if (this.tempCheckedData.has(e.id)) {
              const row = usersTable.getRowById(e.id)
              if (row) {
                usersTable.setCheckboxRow(row, true)
              }
            }
          })
        }
      })
    },
    handleCheckAll ({ records, checked }) {
      const rows = this.$refs.usersTable.getRows()
      if (checked) {
        records.forEach((item) => this.tempCheckedData.add(item.id))
      } else {
        // 注意取消全选时需要遍历当前表格数据来删除，records不管用
        rows.forEach((item) => this.tempCheckedData.delete(item.id))
      }
    },
    handleCheckChange ({ rowid, checked }) {
      if (checked) {
        this.tempCheckedData.add(rowid)
      } else {
        this.tempCheckedData.delete(rowid)
      }
    },
    async handleCellClick ({ row }) {
      this.roleRow = row
      const usersTable = this.$refs.usersTable.getGrid()
      // usersTable.clearSelected() // 手动清除单元格选中状态
      usersTable.setAllCheckboxRow(false) // 清除所有行的选中状态
      this.tempCheckedData = new Set()
      const { data } = await this.$store.dispatch(this.url.roleUserList, {
        roleId: row.id
      })
      if (data) {
        this.roleUserData = [...data]
        data.forEach((element) => {
          const s = usersTable.getRowById(element.userId)
          this.tempCheckedData.add(element.userId)
          if (s) {
            usersTable.setCheckboxRow(s, true)
          }
        })
      }
    },
    async doSave () {
      if (!this.roleRow) {
        this.$utils.message.warning('请选择授权角色！')
        return
      }
      const params = { roleId: this.roleRow.id }
      const userIds = Array.from(this.tempCheckedData)
      if (userIds && userIds.length > 0) {
        params.userIds = userIds
      }
      // console.info('----------ids: ' + JSON.stringify(params))
      const { error } = await this.$store.dispatch(this.url.saveData, params)
      if (!error) {
        this.$utils.message.success('保存成功')
      }
    }
  }
}
</script>
<style lang="scss">
.my-list {
  background-color: #ffffff;
  border: 1px solid #e8eaec;
  height: 100%;
  font-size: 14px;
}
.my-list .my-list-item {
  height: 20px;
  padding: 5px 0 5px 15px;
  border-bottom: 1px solid #e8eaec;
}
</style>
